package com.yeswater.rabbitmq;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.yeswater.rabbitmq.utils.RabbitmqUtil;

import java.io.IOException;

/**
 * 工作线程 相当于消费者
 * Author : yeswater
 */

public class Work implements Runnable {

    public static final String QUEUE_NAME = "mq02";

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        Channel channel = null;
        try {
            channel = RabbitmqUtil.getChannel();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        DeliverCallback deliverCallback = (consumer, message) -> {
            System.out.println(name +"接收到的消息: "+new String(message.getBody()));
        };

        CancelCallback cancelCallback = (consumerTag) -> {
            System.out.println(consumerTag +" 消息消费被中断");
        };

        /**
         * 1.消费的队列
         * 2.消费成功之后是否要自动应答
         * 3.消费者未成功消费的回调
         * 4.消费者取消消费的回调
         */
        System.out.println(Thread.currentThread().getName() + "线程等待接收消息");
        try {
            channel.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
